#include <stdio.h>
#include <stdlib.h>

struct Node
{
    int val;
    struct Node* next;
    struct Node* random;
};

struct Node* copyRandomList(struct Node* head) {
    struct Node* cur = head, * newnode = NULL;
    while (cur)
    {
        newnode = (struct Node*)malloc(sizeof(struct Node));
        newnode->val = cur->val;
        newnode->next = cur->next;
        cur->next = newnode;
        cur = newnode->next;
    }


    cur = head;
    while (cur)
    {
        struct Node* newnode = cur->next;
        if (cur->random == NULL)
        {
            newnode->random = NULL;
        }
        else
        {
            newnode->random = cur->random->next;
        }
        cur = cur->next->next;
    }


    cur = head;
    struct Node* newhead = NULL, * tail = NULL;
    while (cur)
    {
        struct Node* newnode = cur->next;
        struct Node* next = newnode->next;
        if (tail == NULL)
        {
            newhead = tail = newnode;
        }
        else
        {
            tail->next = newnode;
            tail = tail->next;
        }
        cur->next = next;
        cur = next;
    }
    return newhead;
}